package com.doctor.ui.homedoctor;

import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.app.PendingIntent;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.FragmentTransaction;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;

import org.jsoup.Jsoup;
import org.jsoup.safety.Whitelist;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import com.doctor.adapter.ShowImageAdapter;
import com.doctor.bean.DiseaseRecordBean;
import com.doctor.bean.PatientFileBean;
import com.doctor.bean.UserBean;
import com.doctor.comm.ConstConfig;
import com.doctor.comm.DialogHelper;
import com.doctor.comm.FragmentHelper;
import com.doctor.comm.LoadingTip;
import com.doctor.comm.MyApplication;
import com.doctor.comm.MyFont;
import com.doctor.database.DbOperator;
import com.doctor.net.NetUtil;
import com.doctor.ui.BaseFragment;
import com.doctor.ui.DragImageActivity;
import com.doctor.ui.R;
import com.doctor.ui.wxapi.MyWXApi;
import com.doctor.ui.wxapi.WXShare;
import com.doctor.view.NoScrollGridView;

public class LookDiseaseRecordFrag extends BaseFragment{

	/**
	 * 查看病历
	 */
	// for logging
	private static final String TAG = LookDiseaseRecordFrag.class.getSimpleName();
	private Context context;
	private TextView tvTime,tvComplain,tvPresent,tvPrescription,tvPhysicalCheck,tvAuxiliaryCheck,tvInitialDiagnosis,tvDoctorAdvice;
	private LinearLayout printBtn, printBtnDese, healthManagerBtn, sendEmailBtn, sendBluetoothBtn, sendWXBtn;
	private DiseaseRecordBean bean;
	private PatientFileBean patientBean;
	private Click click;
	private HealthManagerFrag healthManagerFrag;
	//显示图片之用
	private NoScrollGridView gridView;
	private ShowImageAdapter adapter;
	private List<String> beanList;
	private String email_txt;
	private UserBean user = DbOperator.getInstance(context).selectUserInfo();
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		context=getActivity();
		bean=(DiseaseRecordBean) getArguments().getSerializable(ConstConfig.BEAN);
		patientBean=(PatientFileBean) getArguments().getSerializable(ConstConfig.BEAN_2);
		click=new Click();
		
		View view=inflater.inflate(R.layout.look_disease_record, container, false);
		initiaView(view);
		
		return view;
	}
	
	@Override
	protected void initiaView(View view) {
		// TODO Auto-generated method stub
		tvTime=(TextView) view.findViewById(R.id.tv_time);
		tvTime.setText(bean.getTime());
		
		tvComplain=(TextView) view.findViewById(R.id.tv_complain);
		tvComplain.setText(bean.getComplain());
		
		tvPresent=(TextView) view.findViewById(R.id.tv_present);
		tvPresent.setText(bean.getPresent());
		
		tvPhysicalCheck=(TextView) view.findViewById(R.id.tv_physical_check);
		tvPhysicalCheck.setText(bean.getPhysicalCheck());
		
		tvAuxiliaryCheck=(TextView) view.findViewById(R.id.tv_auxiliary_check);
		tvAuxiliaryCheck.setText(bean.getAuxiliaryCheck());
		
		tvInitialDiagnosis=(TextView) view.findViewById(R.id.tv_initial_diagnosis);
		tvInitialDiagnosis.setText(bean.getInitialDiagnosis());
		
		tvPrescription=(TextView) view.findViewById(R.id.tv_prescription);
		tvPrescription.setText(bean.getPrescription());	
		
		tvDoctorAdvice = (TextView) view.findViewById(R.id.tv_doctor_advice);
		tvDoctorAdvice.setText(bean.getDoctorAdvice());	
		
		printBtn = (LinearLayout) view.findViewById(R.id.printBtn);
		printBtn.setOnClickListener(click);
		
		printBtnDese= (LinearLayout) view.findViewById(R.id.printBtnDese);
		printBtnDese.setOnClickListener(click);
		
		healthManagerBtn=(LinearLayout) view.findViewById(R.id.healthManagerBtn);
		healthManagerBtn.setOnClickListener(click);
		
		sendEmailBtn=(LinearLayout) view.findViewById(R.id.sendEmailBtn);
		sendEmailBtn.setOnClickListener(click);
		
		sendBluetoothBtn=(LinearLayout) view.findViewById(R.id.sendBluetoothBtn);
		sendBluetoothBtn.setOnClickListener(click);
		
		sendWXBtn = (LinearLayout) view.findViewById(R.id.sendWXBtn);
		sendWXBtn.setOnClickListener(click);
		
		gridView=(NoScrollGridView) view.findViewById(R.id.gridView);
		beanList=new ArrayList<String>();
		adapter=new ShowImageAdapter(context, beanList);
		gridView.setAdapter(adapter);
		gridView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				// TODO Auto-generated method stub
				String picPath=(String) arg1.getTag(R.id.bean_tag);
				Intent intent=new Intent(getActivity(),DragImageActivity.class);
				intent.putExtra(getString(R.string.uri), picPath);
				startActivity(intent);
			}
		});
		gridView.setOnItemLongClickListener(new OnItemLongClickListener() {
			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				// TODO Auto-generated method stub
				if (!MyWXApi.canUseWX()) {
					LoadingTip.showToast(getActivity(), getString(R.string.wx_unuseful));
					return true;
				}
				
				final String picPath = (String) arg1.getTag(R.id.bean_tag);
				DialogHelper.showConfirmCancelDialog(getActivity(), "微信发送病历图片", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface arg0, int arg1) {
						// TODO Auto-generated method stub
						WXShare.sharePic(picPath);
					}
				});
				//无实际作用，主要防止长按后响应onItemClick事件
				return true;
			}
		});
		getImageFromDb();
	}
	
	private class Click implements OnClickListener{
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			if (v == printBtn) {
				//打印
				File tmp;
				try {
					String html = createHtml();
					tmp = saveHtmlToTempFile(html);
					queuePdfFileForPrinting(context, tmp);
				} catch (IOException e) {
					e.printStackTrace();
				}
			} else if (v == printBtnDese) {
				// 打印
				File tmp;
				try {
					String html = createPrescriptionHtml();
					tmp = saveHtmlToTempFile(html);
					queuePdfFileForPrinting(context, tmp);
				} catch (IOException e) {
					e.printStackTrace();
				}
				
			}else if (v==healthManagerBtn) {
				healthManagerFrag=null;
				healthManagerFrag=new HealthManagerFrag();
				Bundle bundle=new Bundle();
				bundle.putInt(ConstConfig.ID, bean.getId());
				healthManagerFrag.setArguments(bundle);
				FragmentTransaction transaction=getActivity().getSupportFragmentManager().beginTransaction();
				FragmentHelper.setFragSwitchAnimation(transaction);
				transaction.replace(R.id.frag_container, healthManagerFrag).addToBackStack(null).commit();
			} else if (v == sendWXBtn) {
				//微信发送档案与病历资料
				if (!MyWXApi.canUseWX()) {
					LoadingTip.showToast(getActivity(), getString(R.string.wx_unuseful));
					return;
				}
				//健康管理内容
				DiseaseRecordBean healthManage = DbOperator.getInstance(MyApplication.getInstance()).getDiseaseRecordHealthManagerById(bean.getId());
				if (healthManage != null) {
					bean.setHealthAna(healthManage.getHealthAna());
					bean.setHealthInstruct(healthManage.getHealthInstruct());
					bean.setHealthDirect(healthManage.getHealthDirect());
				}
				WXShare.sharePatientDiseaseRecord(patientBean, bean);
			} else if (v==sendEmailBtn) {			
				String email_txt=DbOperator.getInstance(context).getFieldById(ConstConfig.PATIENT_FILE_TABLE, bean.getPatientId(), "_email");
				LookDiseaseRecordFrag.this.email_txt=email_txt;
				if (email_txt==null || "".equals(email_txt.trim())) {
					Toast.makeText(context, "患者邮箱未填写！", Toast.LENGTH_SHORT).show();
					return;
				}
				if (!NetUtil.hasNetwork(context)) {
					Toast.makeText(context, "请连接网络！", Toast.LENGTH_SHORT).show();
					return;
				}
				
				ArrayList<String> images=adapter.getPics();
				String healthAna_txt=bean.getHealthAna();
				String healthInstruct_txt=bean.getHealthInstruct();
				String healthDirect_txt=bean.getHealthDirect();
				
				StringBuilder builder=new StringBuilder();
				
				builder.append("<p><b>个人档案：</b><br>");
				String sex=patientBean.getSex();
				if (sex!=null && "男".equals(sex.trim())) {
					sex="男";
				} else if (sex!=null && "女".equals(sex.trim())) {
					sex="女";
				} else {
					sex="";
				}
				builder.append("编号:"+patientBean.getId()+"，"+" 姓名:"+patientBean.getName()+"，"+" 性别:"+sex+"<br>");
				builder.append("婚否:" + (patientBean.getMarriage() != null ? patientBean.getMarriage() : "") + "<br>");
				builder.append("出生日期:"+(patientBean.getBirthDay()!=null?patientBean.getBirthDay()+"，":"")+" 服务截止:"+(patientBean.getEndDay()!=null?patientBean.getEndDay():"")+"<br>");
				builder.append("电话:"+(patientBean.getPhone()!=null?patientBean.getPhone()+"，":"")+" 手机:"+(patientBean.getMobile()!=null?patientBean.getMobile()+"，":"")
						+" 邮箱:"+(patientBean.getEmail()!=null?patientBean.getEmail():"")+"<br>");
				builder.append("地址:"+(patientBean.getAddress()!=null?patientBean.getAddress():"")+"<br>");
				builder.append("体质:"+(patientBean.getBody()!=null?patientBean.getBody()+"，":"")+" 血型:"+(patientBean.getBloodType()!=null?patientBean.getBloodType():"")+"<br>");
				builder.append("联系人:" + (patientBean.getContacts() != null ? patientBean.getContacts() : "") + "<br>");
				builder.append("联系人电话:" + (patientBean.getContactsMobile() != null ? patientBean.getContactsMobile() : "") + "<br>");
				builder.append("药物过敏史:" + (patientBean.getAllergy() != null ? patientBean.getAllergy() : "") + "<br>");
				builder.append("家族史:"+(patientBean.getFamilyHistory()!=null?patientBean.getFamilyHistory():"")+"<br>");
				builder.append("个人史:"+(patientBean.getPersonalHistory()!=null?patientBean.getPersonalHistory():"")+"<br>");
				builder.append("疾病史:"+(patientBean.getDiseaseHistory()!=null?patientBean.getDiseaseHistory():"")+"<br></p>");
				
				builder.append("<p><b>病历资料</b><br>");
				builder.append("就诊时间:" + (bean.getTime() != null ? bean.getTime() : "") + "<br>");
				builder.append("主诉:" + (bean.getComplain() != null ? bean.getComplain() : "") + "<br>");
				builder.append("现病史:" + (bean.getPresent() != null ? bean.getPresent() :"") + "<br>");
				builder.append("体格检查:" + (bean.getPhysicalCheck() != null ? bean.getPhysicalCheck() : "") + "<br>");
				builder.append("辅助检查:" + (bean.getAuxiliaryCheck() != null ? bean.getAuxiliaryCheck() : "") + "<br>");
				builder.append("图片:"+"<br>");
				if (images!=null && images.size()>0) {
					for (String imgPath : images) {
						//从路径中获取图片名
						String imgName=imgPath.substring(imgPath.lastIndexOf("/")+1);
						builder.append("<img src=\""+imgName+"\""+"/>");
					}
					builder.append("<br>");
				}
				builder.append("初步诊断:" + (bean.getInitialDiagnosis() != null ? bean.getInitialDiagnosis() : "") + "<br>");
				builder.append("处方:" + (bean.getPrescription() != null ? bean.getPrescription() : "") + "<br>");
				builder.append("医嘱:" + (bean.getDoctorAdvice() != null ? bean.getDoctorAdvice() : "") + "<br>");
				builder.append("</p>");
				
				if (healthAna_txt!=null && !"".equals(healthAna_txt.trim())) {
					builder.append("<p><b>健康分析:</b><br>"+healthAna_txt+"</p>");
				}
				if (healthInstruct_txt!=null && !"".equals(healthInstruct_txt.trim())) {
					builder.append("<p><b>健康指导:</b><br>"+healthInstruct_txt+"</p>");
				}
				if (healthDirect_txt!=null && !"".equals(healthDirect_txt.trim())) {
					builder.append("<p><b>健康提示:</b><br>"+healthDirect_txt+"</p>");
				}
				String content= builder.append("").toString();
				if (content.length()<=5) {
					Toast.makeText(context, "未填写健康分析、指导、提示内容！", Toast.LENGTH_SHORT).show();
					return;
				}
				
				File dir=new File(ConstConfig.IMG_FILE);
				if (!dir.exists()) {
					dir.mkdirs();
				}
				File healthTip=new File(dir, patientBean.getName()+" "+bean.getComplain()+" "+"健康管理资料.html");
				if (!healthTip.exists()) {
					try {
						healthTip.createNewFile();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				BufferedWriter out = null;
				try {
					out=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(healthTip), "GBK"));
					out.write(content);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} finally {
					try {
						out.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				
				if (images==null) {
					images=new ArrayList<String>();
				}
				images.add(healthTip.getAbsolutePath());
				
				ArrayList<Uri> uris = new ArrayList<Uri>(images.size());
				for (String path : images) {
					uris.add(Uri.fromFile(new File(path)));
				}
				
				Intent sendEmailIntent;
				sendEmailIntent=new Intent(Intent.ACTION_SEND_MULTIPLE);
				sendEmailIntent.putExtra(Intent.EXTRA_EMAIL, email_txt.split(";"));
				sendEmailIntent.putExtra(Intent.EXTRA_SUBJECT, patientBean.getName()+" "+bean.getDisease()+" "+"健康管理");
				sendEmailIntent.putExtra(Intent.EXTRA_TEXT, "请将图片和文件“健康管理资料.html”放在同一文件夹内打开");
				sendEmailIntent.setType("text/plain");
				sendEmailIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
				sendEmailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivityForResult(Intent.createChooser(sendEmailIntent, "选择邮件客户端:"),1);
			} else if (v==sendBluetoothBtn) {
				ArrayList<String> images=adapter.getPics();
				String healthAna_txt=bean.getHealthAna();
				String healthInstruct_txt=bean.getHealthInstruct();
				String healthDirect_txt=bean.getHealthDirect();
				
				StringBuilder builder=new StringBuilder();
				
				builder.append("<p><b>个人档案：</b><br>");
				String sex=patientBean.getSex();
				if (sex!=null && "男".equals(sex.trim())) {
					sex="男";
				} else if (sex!=null && "女".equals(sex.trim())) {
					sex="女";
				} else {
					sex="";
				}
				builder.append("编号:"+patientBean.getId()+"，"+" 姓名:"+patientBean.getName()+"，"+" 性别:"+sex+"<br>");
				builder.append("婚否:" + (patientBean.getMarriage() != null ? patientBean.getMarriage() : "") + "<br>");
				builder.append("出生日期:"+(patientBean.getBirthDay()!=null?patientBean.getBirthDay()+"，":"")+" 服务截止:"+(patientBean.getEndDay()!=null?patientBean.getEndDay():"")+"<br>");
				builder.append("电话:"+(patientBean.getPhone()!=null?patientBean.getPhone()+"，":"")+" 手机:"+(patientBean.getMobile()!=null?patientBean.getMobile()+"，":"")
						+" 邮箱:"+(patientBean.getEmail()!=null?patientBean.getEmail():"")+"<br>");
				builder.append("地址:"+(patientBean.getAddress()!=null?patientBean.getAddress():"")+"<br>");
				builder.append("体质:"+(patientBean.getBody()!=null?patientBean.getBody()+"，":"")+" 血型:"+(patientBean.getBloodType()!=null?patientBean.getBloodType():"")+"<br>");
				builder.append("联系人:" + (patientBean.getContacts() != null ? patientBean.getContacts() : "") + "<br>");
				builder.append("联系人电话:" + (patientBean.getContactsMobile() != null ? patientBean.getContactsMobile() : "") + "<br>");
				builder.append("药物过敏史:" + (patientBean.getAllergy() != null ? patientBean.getAllergy() : "") + "<br>");
				builder.append("家族史:"+(patientBean.getFamilyHistory()!=null?patientBean.getFamilyHistory():"")+"<br>");
				builder.append("个人史:"+(patientBean.getPersonalHistory()!=null?patientBean.getPersonalHistory():"")+"<br>");
				builder.append("疾病史:"+(patientBean.getDiseaseHistory()!=null?patientBean.getDiseaseHistory():"")+"<br></p>");
				
				builder.append("<p><b>病历资料</b><br>");
				builder.append("就诊时间:" + (bean.getTime() != null ? bean.getTime() : "") + "<br>");
				builder.append("主诉:" + (bean.getComplain() != null ? bean.getComplain() : "") + "<br>");
				builder.append("现病史:" + (bean.getPresent() != null ? bean.getPresent() :"") + "<br>");
				builder.append("体格检查:" + (bean.getPhysicalCheck() != null ? bean.getPhysicalCheck() : "") + "<br>");
				builder.append("辅助检查:" + (bean.getAuxiliaryCheck() != null ? bean.getAuxiliaryCheck() : "") + "<br>");
				builder.append("图片:"+"<br>");
				if (images!=null && images.size()>0) {
					for (String imgPath : images) {
						//从路径中获取图片名
						String imgName=imgPath.substring(imgPath.lastIndexOf("/")+1);
						builder.append("<img src=\""+imgName+"\""+"/>");
					}
					builder.append("<br>");
				}
				builder.append("初步诊断:" + (bean.getInitialDiagnosis() != null ? bean.getInitialDiagnosis() : "") + "<br>");
				builder.append("处方:" + (bean.getPrescription() != null ? bean.getPrescription() : "") + "<br>");
				builder.append("医嘱:" + (bean.getDoctorAdvice() != null ? bean.getDoctorAdvice() : "") + "<br>");
				builder.append("</p>");
				
				if (healthAna_txt!=null && !"".equals(healthAna_txt.trim())) {
					builder.append("<p><b>健康分析:</b><br>"+healthAna_txt+"</p>");
				}
				if (healthInstruct_txt!=null && !"".equals(healthInstruct_txt.trim())) {
					builder.append("<p><b>健康指导:</b><br>"+healthInstruct_txt+"</p>");
				}
				if (healthDirect_txt!=null && !"".equals(healthDirect_txt.trim())) {
					builder.append("<p><b>健康提示:</b><br>"+healthDirect_txt+"</p>");
				}
				String content= builder.append("").toString();
				if (content.length()<=5) {
					Toast.makeText(context, "未填写健康分析、指导、提示内容！", Toast.LENGTH_SHORT).show();
					return;
				}
				
				File dir=new File(ConstConfig.IMG_FILE);
				if (!dir.exists()) {
					dir.mkdirs();
				}
				File healthTip=new File(dir, patientBean.getName()+" "+bean.getComplain()+" "+"健康管理资料.html");
				if (!healthTip.exists()) {
					try {
						healthTip.createNewFile();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				BufferedWriter out = null;
				try {
					out=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(healthTip), "GBK"));
					out.write(content);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} finally {
					try {
						out.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				
				if (images==null) {
					images=new ArrayList<String>();
				}
				images.add(healthTip.getAbsolutePath());
				
				ArrayList<Uri> uris = new ArrayList<Uri>(images.size());
				for (String path : images) {
					uris.add(Uri.fromFile(new File(path)));
				}
				
				Intent blueToothIntent=new Intent(Intent.ACTION_SEND_MULTIPLE);
				blueToothIntent.putExtra(Intent.EXTRA_EMAIL, "蓝牙发送");
				blueToothIntent.putExtra(Intent.EXTRA_SUBJECT, "蓝牙发送");
				blueToothIntent.putExtra(Intent.EXTRA_TEXT, "请将图片和文件“健康管理资料.html”放在同一文件夹内打开");
				blueToothIntent.setType("text/plain");
				blueToothIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
				blueToothIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivityForResult(Intent.createChooser(blueToothIntent, "选择蓝牙发送:"),3);
			}
		}
	}
	
	/**
	 * 从数据库查询图片uri
	 */
	private void getImageFromDb(){
		new Thread() {
			public void run() {
				try {
					sleep(DbOperator.delayTime);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				String images=DbOperator.getInstance(context).selectImages(ConstConfig.DISEASE_RECORD_TABLE, bean.getId());
				if (images!=null && !"".equals(images)) {
					String[] imageArray= images.split(ConstConfig.IMAGE_SPLIT);
					for (String image : imageArray) {
						beanList.add(image);
					}
					getActivity().runOnUiThread(new Runnable() {	
						@Override
						public void run() {
							// TODO Auto-generated method stub
							adapter.notifyDataSetChanged();
						}
					});
				}
			}
		}.start();
	}	
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		switch (requestCode) {
		case 1:
			String mobile=DbOperator.getInstance(context).getFieldById(ConstConfig.PATIENT_FILE_TABLE, bean.getPatientId(), "_mobile");
			if (mobile==null || "".equals(mobile)) {
				Toast.makeText(getActivity(), "未设置手机号，不能发送提示短信！", Toast.LENGTH_SHORT).show();
				return;
			}	
			SmsManager smsManager=SmsManager.getDefault();
			Intent sendIntent=new Intent("SENT_SMS_ACTION");
			PendingIntent sendPi=PendingIntent.getBroadcast(context, 4, sendIntent, 0);
			String message="健康管理档案已发送至"+email_txt+"邮箱，请查收。";
			smsManager.sendTextMessage(mobile, null, message, sendPi, null);
			ContentValues values=new ContentValues();
			values.put("date", System.currentTimeMillis());
			values.put("read", 0);
			values.put("type", 2);
			values.put("address", mobile);
			values.put("body", message);
			//写入短信库
			context.getContentResolver().insert(Uri.parse("content://sms/sent"), values);
			break;

		case 3: //蓝牙
			break;
			
		case 4: //短信发送成功
			Toast.makeText(context, "健康提示短信发送成功！", Toast.LENGTH_SHORT).show();
			break;
			
		default:
			break;
			
		}
		
	}
	
	
	@Override
	public void onDestroyView() {
		// TODO Auto-generated method stub
		super.onDestroyView();
		if (adapter != null) {
			adapter.clear();
		}
	}
	
	/**
	 * 生成html页面
	 * 
	 * @return
	 */
	public String createHtml() {
		
		bean = DbOperator.getInstance(context).getDiseaseRecord(bean.getId());
		int age =0;
		try
		{
		if(patientBean.getBirthDay()!=null)
		{
			SimpleDateFormat sdf =   new SimpleDateFormat("yyyy-MM-dd");
			Date birth = sdf.parse(patientBean.getBirthDay());
			age = new Date().getYear()-birth.getYear();
		}
		}catch(Exception e){}

		Date currentTime = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String dateString = formatter.format(currentTime);
		StringBuilder buf = new StringBuilder();
		buf.append("<html> <head><style>*{ font-family:my_font; font-size:14px;} body{ margin:0; } .tb{ border-spacing: 1px;background: #000;width:100%; margin:auto; } .tb td {background:#fff; padding:10px 0;  } .w1 { 	width:20%; } .w4 { 	width:30%; }.w5 { 	width:50%; }.w9 { 	width:80%; } </style></head> <body>" +
				"<table class='tb' style='border-spacing:0;background:#fff;margin-top:20px;'>" +
				"<tr><td style='font-size:26px;text-align:center;height:40px;'>"+user.getLocalHospital()+"</td></tr>" +
				"<tr><td style='font-size:26px;font-weight:bold;text-align:center;height:40px;'>处方笺</td></tr>" +
				"</table><table class='tb'> "
				+ "<tr> <td class='w1'>编号:</td> <td colspan='2' class='w3'>"
				+ patientBean.getId()
				+ " </td><td colspan='3' class='w5'>打印时间:"+dateString+"</td> </tr> "
				+ "<tr> <td class='w1'>姓名:</td> <td>"
				+ patientBean.getName()
				+ " </td><td>性别:</td><td>"+patientBean.getSex()+"</td> <td>年龄:</td><td>"+age+"</td> </tr> "
				+ "<tr> <td class='w1'>地址:</td> <td colspan='5' class='w9'>"
				+ patientBean.getAddress()
				+ " </td> </tr> "
				+ "<tr> <td class='w1'>初步诊断:</td> <td colspan='5' class='w9'>"
				+ bean.getInitialDiagnosis()
				+ " </td> </tr> </table>"
				+ "<table style='border-bottom:1px solid #000;'><tr><td colspan='6' rowspan='6' style='height:450px;' valign='top'><p style='font-size:24px;font-weight:bold;margin:20px 0;'>R</p> "
				+ "<div style='width:500px;'>"+bean.getPrescription()+"</div>"
				+ "</td> </tr></table> " +
				"<table style='border-bottom:1px solid #000;width:100%;height:40px;'><tr><td style='padding:10px 0;'>医师签名:"+user.getLocalName()+"</td><td style='padding:10px 0;'>调配:</td><td style='padding:10px 0;'>复核:</td></tr><tr style='background:#000;'><td colspan='3'></td></tr>" +
				"<tr><td colspan='3' style='padding:10px 0;'>药品金额:￥</td></tr><tr style='background:#000;'><td colspan='3'></td></tr> </table></body> </html>");
		String str = buf.toString().replace("null", "");
		return str;
	}

	public String createPrescriptionHtml() {
		bean = DbOperator.getInstance(context).getDiseaseRecord(bean.getId());
		
		Date currentTime = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String dateString = formatter.format(currentTime);
		StringBuilder buf = new StringBuilder();
		buf.append("<html> <head><style>*{ font-family:my_font;font-size:14px; }div{margin:5px 0; line-height:25px;} body{ margin:0; } .tb{ border-spacing: 1px;background: #000;width:100%; margin:auto; } .tb td {background:#fff; padding:10px 0;  } .w1 { 	width:20%; } .w4 { 	width:30%; }.w5 { 	width:50%; }.w9 { 	width:80%; } </style></head> <body>" +
				"<table class='tb' style='border-spacing:0;background:#fff;'>" +
				"<tr><td style='font-size:26px;text-align:center;height:40px;margin-top:20px;'>"+user.getLocalHospital()+"</td></tr>" +
				"<tr><td style='font-size:26px;font-weight:bold;text-align:center;height:40px;'>电子病历</td></tr>" +
				"</table><table class='tb'> "
				+ "<tr> <td class='w1'>编号:</td> <td colspan='2' class='w3'>"
				+ patientBean.getId()
				+ " </td><td colspan='3' class='w5'>打印时间:"+dateString+"</td> </tr> "
				+ "<tr> <td class='w1'>姓名:</td> <td>"
				+ patientBean.getName()
				+ " </td><td>性别:</td><td>"+patientBean.getSex()+"</td> <td>出生日期:</td><td>"+patientBean.getBirthDay()+"</td> </tr> "
				+ "<tr> <td class='w1'>体质:</td> <td>"
				+ patientBean.getBody()
				+ " </td><td>血型:</td><td>"+patientBean.getBloodType()+"</td> <td>婚否:</td><td>"+patientBean.getMarriage()+"</td> </tr> "
				+ "<tr> <td class='w1'>地址:</td> <td colspan='5' class='w9'>"
				+ patientBean.getAddress()
				+ " </td> </tr> "
				+ "<tr> <td class='w1'>药物过敏史:</td> <td colspan='5' class='w9'>"
				+ patientBean.getAllergy()
				+ " </td> </tr> "
				+ "<tr> <td class='w1'>家族史:</td> <td colspan='5' class='w9'>"
				+ patientBean.getFamilyHistory()
				+ " </td> </tr> "
				+ "<tr> <td class='w1'>个人史:</td> <td colspan='5' class='w9'>"
				+ patientBean.getPersonalHistory()
				+ " </td> </tr> "
				+ "<tr> <td class='w1'>疾病史:</td> <td colspan='5' class='w9'>"
				+ patientBean.getDiseaseHistory()
				+ " </td> </tr> "
				+ "<tr><td colspan='6' style='height:370px;' valign='top'>"
				+ "<div style='width:500px;'>就诊时间:"+bean.getTime()+"</div>" 
				+ "<div style='width:500px;'>主诉:"+bean.getComplain()+"</div>" 
				+ "<div style='width:500px;'>现病史:"+bean.getPresent()+"</div>" 
				+ "<div style='width:500px;'>体格检查:"+bean.getPhysicalCheck()+"</div>" 
				+ "<div style='width:500px;'>辅助检查:"+bean.getAuxiliaryCheck()+"</div>" 
				+ "<div style='width:500px;'>初步诊断:"+bean.getInitialDiagnosis()+"</div>" 
				+ "<div style='width:500px;'>处方:"+bean.getPrescription()+"</div>" 
				+ "<div style='width:500px;'>医嘱:"+bean.getDoctorAdvice()+"</div>" 
				+ "</td> </tr> </table> " +
				"<div style='padding-left:300px;margin-top:10px;'>医师签名:"+user.getLocalName()+"</div> </body> </html>");
		String str = buf.toString().replace("null", "");
		return str;
	}

	/**
	 * 打印PDF
	 * 
	 * @param context
	 * @param f
	 * @return
	 */
	public boolean queuePdfFileForPrinting(Context context, File f) {
		// send to print activity
		Uri uri = Uri.fromFile(f);
		Intent i = new Intent(Intent.ACTION_SEND);
		i.setPackage("com.hp.android.printservice");
		i.setDataAndType(uri, "application/pdf");
		i.putExtra("deleteAfterPrint", true);
		context.startActivity(i);

		return true;
	}

	/**
	 * 把html字符串生成pdf文档
	 * 
	 * @param html
	 * @return
	 * @throws IOException
	 */
	public File saveHtmlToTempFile(String html) throws IOException {
		File tempFile = null;

		// save to temporary file
		File dir = getTempDir();
		if (dir != null) {
			try {
				File f = File.createTempFile("pdf", ".pdf", dir);
				tempFile = createPDF(html, f.getPath().replace(".pdf", "1.pdf"));
			} finally {
			}
		}

		return tempFile;
	}

	/**
	 * 创建临时目录
	 * 
	 * @return
	 */
	public File getTempDir() {
		File dir = new File(Environment.getExternalStorageDirectory(), "temp");
		if (dir.exists() == false && dir.mkdirs() == false) {
			Log.e(TAG, "failed to get/create temp directory");
			return null;
		}
		return dir;
	}

	/**
	 * 生成pdf中文字体
	 * 
	 * @return
	 */
	public static Font setChineseFont() {
		BaseFont bf = null;
		Font fontChinese = null;
		try {
			bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",
					BaseFont.NOT_EMBEDDED);
			fontChinese = new Font(bf, 12, Font.NORMAL);
		} catch (DocumentException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return fontChinese;
	}

	/**
	 * html字符串转成PDF
	 * 
	 * @param rawHTML
	 * @param f
	 * @return
	 */
	public static File htmlCodeComeString(String html, String path) {
		File tempFile = null;
		Document doc = new Document();
		FileOutputStream fos;
		try {
			File f = new File(path);
			fos = new FileOutputStream(f);
			PdfWriter.getInstance(doc, fos);
			doc.open();
			doc.add(new Paragraph(html, setChineseFont()));
			// 一定要记得关闭document对象
			doc.close();
			fos.flush();
			fos.close();
			tempFile = f;
		} catch (FileNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return tempFile;
	}

	public static File createPDF(String rawHTML, String fileName) {
		File file = new File(fileName);

		try {

			Rectangle pageSize = new Rectangle(380, 600);
			Document document = new Document(pageSize);

			document.setMargins(1, 1, 1, 1);
			PdfWriter writer = PdfWriter.getInstance(document,
					new FileOutputStream(file));
			document.open();
			// String
			// css="<style>*{ font-family:my_font; } body{ margin:0; } .tb{ width:98%; border-top:1px solid #aaa; border-collapse:collapse; margin:auto; } .tb td { padding:7px 0; border-bottom:1px solid #aaa; } .w1 { 	width:10%; } .w4 { 	width:40%; }.w9 { 	width:90%; } </style>";
			// HTML
			ByteArrayInputStream inputStream = new ByteArrayInputStream(
					rawHTML.getBytes());
			// ByteArrayInputStream cssinput = new ByteArrayInputStream(
			// css.getBytes() );

			// PDF
			XMLWorkerHelper.getInstance().parseXHtml(writer, document,
					inputStream, null, Charset.defaultCharset(), new MyFont());

			document.close();
			return file;

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (DocumentException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}	
	
}
